<template>
  <div class="topbar">
    <!-- 版心 -->
    <div class="wrap wrapTopbar">
      <div class="l">欢迎来到叩丁狼积分商城</div>
      <!-- 右侧菜单 -->
      <ul class="r">
        <li>
          <img :src="userInfo.headImg" class="avator" alt="" />
          用户名：{{ userInfo.nickName }}
        </li>
        <li>我的积分：{{ userInfo.cartTotal }}</li>
        <li>获取积分</li>
        <li>叩丁狼官网</li>

        <li class="cart-btn" v-if="isLogined">
          <img src="../assets/images/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>
        <li class="login-btn" @click="chanisShowLoginModal(true)" v-else>
          登录
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { WeixinLoginAPI } from "@/request/api";
export default {
  created() {
    // 只要用户扫码了,页面会重新刷新,此时可以获取下code值
    // [!!!有可能会获取不到code...$nextTick()!!!]
    this.$nextTick(async () => {
      // console.log("this.$route", this.$route.query.code);
      let mycode = this.$route.query.code;
      if (!mycode) {
        // 获取token
        let mytoken = localStorage.getItem("x-auth-token");
        this.changeIsLogin(Boolean(mytoken));
        if (mytoken) {
          // 登录状态
          console.log("*更新用户信息...");
          this.asyncChangeupdateUserInfo();
        } else {
          // 未登录状态-初始化用户信息
          console.log("*执行了初始化...");
          this.initUserInfo();
        }
        return;
      }
      // 当有code时,就可以直接发起微信扫码登录请求
      let res = await WeixinLoginAPI({
        code: mycode,
      });
      // console.log("WeixinLoginAPI:", res);
      // 0 400 407
      if (res.code == 0) {
        // 1.提示登录成功
        // alert('登录成功')
        this.asyncIsShowToast({
          msg: "登录成功",
          type: "success",
        });
        // 2.保存token
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 3.改变登录状态(切换购物车)
        this.changeIsLogin(true);
        // this.$router.path(this.$route.path)
        // 请求用户信息
        this.asyncChangeupdateUserInfo();
      } else if (res.code == 400) {
        // 提示用户重新扫码
        // 1.提示二维码失效
        // alert('请重新扫码二维码')
        this.asyncIsShowToast({
          msg: "请重新扫描二维码",
          type: "warning",
        });
        // 2.把登录模态框打开
        this.chanisShowLoginModal(true);
      } else if (res.code == 407) {
        // 1.提示用户再使用手机验证码登录一次
        // alert('请使用手机号验证码登录一次');
        this.asyncIsShowToast({
          msg: "请使用手机号验证码登录一次",
          type: "warning",
        });
        // 2.把登录模态框打开
        this.chanisShowLoginModal(true);
        // 储存uuid (登录时取)
        localStorage.setItem("uuid", res.uuid);
      }
    });
  },
  data() {
    return {};
  },
  methods: {
    ...mapMutations({
      chanisShowLoginModal: "showModal/chanisShowLoginModal",
      changeIsLogin: "loginStatus/changeIsLogin",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncChangeupdateUserInfo: "userInfo/asyncChangeupdateUserInfo",
      asyncIsShowToast: "showToast/asyncIsShowToast",
    }),
  },
  computed: {
    ...mapState({
      isLogined: (state) => state.loginStatus.isLogined,
      cartTotal: (state) => state.userInfo.cartTotal,
      userInfo: (state) => state.userInfo.userInfo,
      coin: (state) => state.userInfo.coin,
      headImg: (state) => state.userInfo.headImg,
    }),
  },
  watch: {
    /* // 通过监听路由方式,切换登录状态(方式一)
    // 监听路有变化
      '$route.path':{
        handler(newVal,oldVal){
          console.log('$route.path',newVal,oldVal);
          // 路由地址变化后,判断当前用户tiken是否存在
          // 如果存在更新登录状态为true
          // 如果不存在更新登录状态为false
          let mytoken = localStorage.getItem("x-auth-token")
          if(mytoken){
            console.log('登录状态 true');
            this.changeIsLogin(true)
          }else{
            console.log('登录状态 false');
            this.changeIsLogin(false)
          }
          // 优化简写
          // this.changeIsLogin(Boolean(mytoken))
        }
      } */
  },
};
</script>
 
<style lang = "less" scoped>
.topbar {
  height: 40px;
  background: #242b39;
  font-size: 14px;
  font-family: SourceHanSansSC;
  font-weight: 300;
  color: #fffefe;
  line-height: 40px;
  .wrapTopbar {
    display: flex;
    justify-content: space-between;
    .r {
      li {
        float: left;
        margin-left: 20px;
        cursor: pointer;
        text-align: center;
        &.login-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
        }
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
      }
      .avator {
        width: 22px;
        vertical-align: middle;
        border-radius: 50%;
      }
    }
  }
}
</style>